package cn.iocoder.yudao.framework.magic.config.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.api.oauth2.OAuth2TokenApi;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenCheckRespDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.exception.MagicLoginException;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserNickname;


/**
 * 自定义用户名密码登录
 */
@RequiredArgsConstructor
public class AuthorizationInterceptorCustom implements AuthorizationInterceptor {


    private final OAuth2TokenApi oauth2TokenApi;

    /**
     * 配置是否需要登录
     */
    @Override
    public boolean requireLogin() {
        return true;
    }

    /**
     * 根据Token获取User
     */
    @Override
    public MagicUser getUserByToken(String token) throws MagicLoginException {
        // 从上下文获取
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser != null) {
            return new MagicUser(loginUser.getId().toString(), SecurityFrameworkUtils.getLoginUserNickname(),token);
        }

        // 如果上下文没拿到，那就是ws过来的请求，根据token获取
        OAuth2AccessTokenCheckRespDTO accessToken = oauth2TokenApi.checkAccessToken(token).getCheckedData();

        if (accessToken != null) {
            return new MagicUser(accessToken.getUserId().toString(), MapUtil.getStr(accessToken.getUserInfo(), LoginUser.INFO_KEY_NICKNAME),token);
        }

        // 兜底，没拿到用户
        throw new MagicLoginException("token无效");
    }

}
